package com.zeny.express.framework.webapp.filter;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import com.zeny.express.framework.webapp.support.ModuleManager;

/**
 * 框架过滤器，功能： 1)module中的page复制到war工程中 2)增加国际化支持
 * 
 * @author zhuwei
 * @date 2013年8月28日 下午3:03:17
 */
public class FrameworkFilter extends OncePerRequestFilter {

	/**
	 * 是否国际化
	 */
	private boolean localization = true;

	/**
	 * @param localization
	 */
	public void setLocalization(boolean localization) {
		this.localization = localization;
	}

	/**
	 * 初始化bean方法
	 * 
	 * @author zhuwei
	 * @date 2013年8月28日 下午3:05:42
	 * @see org.springframework.web.filter.GenericFilterBean#initFilterBean()
	 */
	@Override
	protected void initFilterBean() throws ServletException {
		// 模块导出页面到WAR工程中
		ModuleManager.export(this.getServletContext());
	}

	/**
	 * 过滤器实现方法
	 * 
	 * @param request
	 *            the current request
	 * @param response
	 *            the current response
	 * @param chain
	 *            the chain
	 * @throws IOException
	 *             when something goes wrong
	 * @throws ServletException
	 *             when a communication failure happens
	 */
	public void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		if (localization) {
			String locale = request.getParameter("locale");
			Locale preferredLocale = null;

			if (locale != null) {
				int indexOfUnderscore = locale.indexOf('_');
				if (indexOfUnderscore != -1) {
					String language = locale.substring(0, indexOfUnderscore);
					String country = locale.substring(indexOfUnderscore + 1);
					preferredLocale = new Locale(language, country);
				} else {
					preferredLocale = new Locale(locale);
				}
			}

			if (preferredLocale != null
					&& !(request instanceof LocaleRequestWrapper)) {
				request = new LocaleRequestWrapper(request, preferredLocale);
				LocaleContextHolder.setLocale(preferredLocale);
			}

			chain.doFilter(request, response);

			// Reset thread-bound LocaleContext.
			LocaleContextHolder.setLocaleContext(null);
		}
	}

}
